package cn.sdormitory.controller;

import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.common.annotation.IgnoreAuth;
import cn.sdormitory.common.annotation.SysLog;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.api.UploadResult;
import cn.sdormitory.common.dto.ResultMsg;
import cn.sdormitory.common.enums.BusinessType;
import cn.sdormitory.common.exception.ApiException;
import cn.sdormitory.service.AppRepairService;
import cn.sdormitory.smartdor.entity.SdRepair;
import cn.sdormitory.smartdor.vo.DeviceVo;
import cn.sdormitory.smartdor.vo.RepairInfoVo;
import cn.sdormitory.smartdor.vo.RepairStaVo;
import cn.sdormitory.smartdor.vo.RepairVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @创建人：zhouyang
 * @创建时间：2021/10/27 23:17
 * @version：V1.0
 */
@RestController
@RequestMapping("/app/Repair")
@Api("APP端报修管理接口")
public class AppRepairController {
    @Autowired
    private AppRepairService appRepairService;
    @Autowired
    private BDormitoryService bDormitoryService;

    @ApiOperation(value = "APP端根据当前登录用户查询报修列表")
    @GetMapping("/findAppRepairByRepairUserId/{userId}")
    public ResultMsg findAppRepairByRepairUserId(@PathVariable Long userId){
        if(userId == null){
            return ResultMsg.BY_FAIL("当前登录用户ID为空");
        }
        List<RepairVo> repairVosList = appRepairService.findAppRepairByRepairUserId(userId);
        return  ResultMsg.BY_SUCCESS("获取成功",repairVosList);
    }

    @ApiOperation(value = "APP端报修列表")
    @GetMapping("/getAppRepair")
    public ResultMsg getAppRepair(String repairDate, String storey,String buildingNo) {
        List<RepairVo> repairVosList=appRepairService.getAppRepair(repairDate,storey,buildingNo);
        return  ResultMsg.BY_SUCCESS("获取成功",repairVosList);
    }

    @ApiOperation(value = "APP端设备列表")
    @GetMapping("/getAppDevice")
    public ResultMsg getAppDevice() {
        List<DeviceVo> deviceVos=appRepairService.getAppDevice();
        return  ResultMsg.BY_SUCCESS("获取成功",deviceVos);
    }

    @ApiOperation(value = "APP端根据宿舍ID及报修日期查询报修详细信息")
    @GetMapping("/getAppRepairByBId")
    public ResultMsg getAppRepairByBId(Long bdormitoryId, String repairDate) {
        List<RepairVo> repairVo=appRepairService.getAppRepairByBId(bdormitoryId,repairDate);
        return  ResultMsg.BY_SUCCESS("获取成功",repairVo);
    }


    @ApiOperation(value="APP端新建报修信息(不带图片)")
    @PostMapping(value = "/createRepair")
    public CommonResult<Integer> create(@RequestBody SdRepair repair) throws IOException {
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(repair.getBdormitoryId());
        repair.setDormitoryNo(bDormitory.getDormitoryNo());
        repair.setBuildingNo(bDormitory.getBuildingNo());
        repair.setStorey(bDormitory.getStorey());
        int count = appRepairService.create(repair);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation(value="APP端修改报修信息(不带图片)")
    @PostMapping(value = "/updateRepair")
    public CommonResult<Integer> update(@RequestBody SdRepair repair) {
        int count = appRepairService.update(repair.getId(), repair);
        if (count > 0) {
            return CommonResult.success(count);
        }

        return CommonResult.failed();
    }

    //上传报修照片
    @PostMapping("/upload")
    public UploadResult upload(MultipartFile photo, HttpServletRequest request) throws IOException {
        InputStream inputStream=photo.getInputStream();
        byte[] iconData=new byte[(int)photo.getSize()];
        inputStream.read(iconData);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        UploadResult result = new UploadResult();

        //获取文件上传地址的真实路径
        String realPath =request.getSession().getServletContext().getRealPath("/uploadFile/");
        System.out.println("---------- "+request.getSession().getServletContext()
                .getRealPath("/"));
        String format = sdf.format(new Date());
        //构建文件对象
        File folder = new File(realPath+format);
        if(!folder.isDirectory()){ // 判断目录是否存在
            folder.mkdirs();  // 创建目录
        }
        // 获取上传文件的逻辑名称
        String oldName = photo.getOriginalFilename();
        // 给文件重命名，避免文件重名
        String newName = UUID.randomUUID().toString()+oldName
                .substring(oldName.lastIndexOf("."),oldName.length());
        try{
            // 上传文件至指定的目录
            photo.transferTo(new File(folder,newName));
            //获取文件上传后的完整地址
            String filePath = request.getScheme()+"://"+
                    request.getServerName()+":"+request.getServerPort()+""+request.getContextPath()+
                    "/uploadFile/"+format+newName;
            System.out.println("filePath:"+filePath);
            result.setSuccess(true);
            result.setMessage(filePath);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 文件上传（表单和文件同步上传）
     *
     * @returncreate
     */
    @ApiOperation(value="createRepairUpload => 新建报修信息（包含图片）")
    @PostMapping(value = "/createRepairUpload")
    public CommonResult saveStu(@RequestParam(value = "upload") MultipartFile upload, SdRepair sdRepair) {
        if (upload.isEmpty()) {
            return CommonResult.failed("未上传照片");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

        byte[] pictureData = null;
        // 使用输入流获取上传的图片
        InputStream inputStream = null;
        try {
            inputStream = upload.getInputStream();
            // 定义字节数组用于存放图片信息
            pictureData = new byte[(int) upload.getSize()];
            // 读取图片到字节数组中
            inputStream.read(pictureData);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String[] split = sdRepair.getDeviceStr().split(",");
        List<Long> deviceList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            deviceList.add(Long.valueOf(split[i]));
        }
        sdRepair.setDeviceIds(deviceList);
        sdRepair.setPhoto(pictureData);
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(sdRepair.getBdormitoryId());
        sdRepair.setDormitoryNo(bDormitory.getDormitoryNo());
        sdRepair.setBuildingNo(bDormitory.getBuildingNo());
        sdRepair.setStorey(bDormitory.getStorey());
        int count = appRepairService.create(sdRepair);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }


    /**
     * 获取图片
     *
     * @param id
     * @param width
     * @param height
     * @param response
     * @throws IOException
     */
    @IgnoreAuth
    @ApiOperation("/getPhoto.do => 获取被修改的图片")
    @GetMapping("/getPhoto.do")
    public void getPhotoById(Long id, int width, int height, final HttpServletResponse response) throws IOException {
        SdRepair repairInfo = appRepairService.getRepairInfoById(id);
        byte[] data = repairInfo.getPhoto();
        if (width != 0 && height != 0) {
            data = scaleImage(data, width, height);
        }
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputSream.write(buf, 0, len);
        }
        outputSream.close();
    }

    /**
     * 显示图片
     *
     * @param data   byet流
     * @param width  图片的宽度
     * @param height 图片的高度
     * @return 2020.11.19
     * @throws IOException
     */
    public static byte[] scaleImage(byte[] data, int width, int height) throws IOException {
        BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
        int imageOldWidth = buffered_oldImage.getWidth();
        int imageOldHeight = buffered_oldImage.getHeight();
        double scale_x = (double) width / imageOldWidth;
        double scale_y = (double) height / imageOldHeight;
        double scale_xy = Math.min(scale_x, scale_y);
        int imageNewWidth = (int) (imageOldWidth * scale_xy);
        int imageNewHeight = (int) (imageOldHeight * scale_xy);
        BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
        buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
        buffered_newImage.getGraphics().dispose();
        ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
        ImageIO.write(buffered_newImage, "jpeg", outPutStream);
        return outPutStream.toByteArray();
    }

    @ApiOperation("updateRepairUpload/ => 修改报修信息(包含图片)")
    @PostMapping (value = "/updateRepairUpload")
    public CommonResult<Integer> updateAndUpload(SdRepair repair, @RequestParam(value = "upload") MultipartFile upload) {
        //根据宿舍ID查询宿舍号
        BDormitory bDormitory=bDormitoryService.getBDormitoryById(repair.getBdormitoryId());
        repair.setDormitoryNo(bDormitory.getDormitoryNo());
        repair.setBuildingNo(bDormitory.getBuildingNo());
        repair.setStorey(bDormitory.getStorey());
        if (upload.isEmpty()) {
            int count = appRepairService.update(repair.getId(), repair);
        } else {
            byte[] pictureData = null;
            // 使用输入流获取上传的图片
            InputStream inputStream = null;
            try {
                inputStream = upload.getInputStream();
                // 定义字节数组用于存放图片信息
                pictureData = new byte[(int) upload.getSize()];
                // 读取图片到字节数组中
                inputStream.read(pictureData);
                repair.setPhoto(pictureData);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int count = appRepairService.update(repair.getId(), repair);
            if (count > 0) {
                return CommonResult.success(count);
            }
        }
        return CommonResult.failed();
    }


    @ApiOperation(value="updateRepairStatus => 修改报修状态")
    @PostMapping(value = "/updateRepairStatus")
    public CommonResult<Integer> update(Long id, String status) {
        int count = appRepairService.updateStatus(id, status);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "APP端统计各状态的报修单数")
    @GetMapping("/getAppRepairCount")
    public ResultMsg getAppRepairCount() {
        RepairStaVo repairStaVo=appRepairService.getAppRepairCount();
        return  ResultMsg.BY_SUCCESS("获取成功",repairStaVo);
    }

    @ApiOperation(value = "APP端获取最新报修单列表")
    @GetMapping("/getAppNewRepairList")
    public ResultMsg getAppNewRepairList() {
        List<RepairInfoVo> repairInfoVo=appRepairService.getAppNewRepairList();
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端获取维修处理中报修单列表")
    @GetMapping("/getAppProcessRepList")
    public ResultMsg getAppProcessList() {
        List<RepairInfoVo> repairInfoVo=appRepairService.getAppProcessList();
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端获取历史报修单据列表")
    @GetMapping("/getAppHistoryRepList")
    public ResultMsg getAppHistoryRepList() {
        List<RepairInfoVo> repairInfoVo=appRepairService.getAppHistoryRepList();
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端根据宿舍ID获取历史报修记录")
    @GetMapping("/getAppHisRepListByBId")
    public ResultMsg getAppHisRepListByBId(Long bdormitoryId) {
        List<RepairInfoVo> repairInfoVo=appRepairService.getAppHisRepListByBId(bdormitoryId);
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端根据报修ID获取报修详情")
    @GetMapping("/getRepairInfoById")
    public ResultMsg getRepairInfoById(Long repairId) {
        SdRepair repairInfoVo=appRepairService.getRepairInfoById(repairId);
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端根据报修ID获取最新报修列表")
    @GetMapping("/getNewRepairInfoById")
    public ResultMsg getNewRepairInfoById(Long bdormitoryId) {
        List<RepairInfoVo> repairInfoVo=appRepairService.getNewRepairInfoById(bdormitoryId);
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @ApiOperation(value = "APP端查询提交人提交的维修列表，包含住宿和班级")
    @GetMapping("/getAllRepairByCreatedBy")
    public ResultMsg getAllRepairByCreatedBy(String username) {
        List<RepairInfoVo> repairInfoVo=appRepairService.getAllRepairByCreatedBy(username);
        return  ResultMsg.BY_SUCCESS("获取成功",repairInfoVo);
    }

    @PostMapping("/deleteRepair")
    public CommonResult deleteRepair(@RequestBody SdRepair repair) {
        int num = appRepairService.deleteRepair(repair.getId(),repair);
        if (num > 0) {
            return CommonResult.success(num);
        }
        return CommonResult.failed();
    }

}
